import {createRouter, createWebHistory, RouterOptions} from 'vue-router';
import global from '@/utils/global.ts';
import {usersInfo} from '@/api/center/login.ts';
import {useUserStore, useAppStore} from '@/store/index.ts';
import {delTokenInfo, getAccessToken} from '@/utils/token.ts';
import {finishLoadingBar, startLoadingBar} from '@/naive/api/index.ts';

export const pathMatch = {
  list: [
    global.loginPage.path,
    '^/unknown',
    '^/error',
    '^/front/.*$'
  ],
  /**
   * 输入路径是否匹配白名单
   * @param path
   * @returns {boolean}
   */
  white: (path: string | undefined | null): boolean => {
    if (path !== undefined && path !== null && path !== '') {
      const whites = pathMatch.list;
      for (let i = 0; i < whites.length; i++) {
        const white = whites[i];
        if (white !== undefined && white !== null && white !== '') {
          if (path === white || path.match(new RegExp(white, 'g'))) {
            return true;
          }
        }
      }
    }
    return false;
  },
  /**
   * 输入路径是否匹配主路径
   * @param path
   * @returns {boolean|*}
   */
  main: (path: string | undefined | null): boolean => {
    if (path !== undefined && path !== null && path !== '') {
      if (path.match(/^\/main\/.*/)) {
        return true;
      }
    }
    return false;
  },
  /**
   * 输入路径是否匹配错误路径
   * @returns {boolean|*}
   */
  error: (name: string | symbol | undefined | null): boolean => {
    return name !== undefined && name !== null && (name === 'error' || name === 'unknown');
  },
  /**
   * 输入路径是否匹配错误路径
   * @returns {boolean|*}
   */
  errorMain: (name: string | symbol | undefined | null): boolean => {
    return name !== undefined && name !== null && (name === 'main:error' || name === 'main:unknown');
  }
};

const router = createRouter(<RouterOptions>{
  strict: true,
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: global.mainPage.path,
      name: global.mainPage.name,
      component: () => import('@/views/layout/main/index.vue'),
      children: [
        {
          path: global.homePage.path,
          name: 'main:home',
          component: () => import('@/views/pages/home/index.vue')
        },
        {
          path: '/main',
          redirect: '/main/home'
        },
        {
          path: '/main/',
          redirect: '/main/home'
        },
        {
          path: '/main/:catchAll(.*)',
          name: 'main:unknown',
          component: () => import('@/views/error/unknown/index.vue')
        },
        {
          path: '/main/:pathMatch(.*)*',
          redirect: '/main/'
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/layout/login/index.vue')
    },
    {
      path: '/',
      name: 'index',
      redirect: '/main'
    },
    {
      path: '',
      redirect: '/main'
    },
    {
      path: '/',
      redirect: '/main'
    },
    {
      path: '/:catchAll(.*)',
      name: 'unknown',
      component: () => import('@/views/error/unknown/index.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/'
    }
  ]
});

router.beforeEach(async (to, from, next) => {
  // console.log('router.before >>> to = ', to, '\tfrom = ', from);
  // do before to view
  // 判断是否前往登录页面
  startLoadingBar();
  if (pathMatch.error(to.name)) {
    // console.log('to error [1]', to.path);
    next();
  } else if (pathMatch.main(to.path)) {
    if (pathMatch.white(to.path)) {
      // console.log('to path white [3]');
      next();
    } else {
      const accessToken = getAccessToken();
      if (!accessToken) {
        // console.log('to path login [4]');
        // 未登录跳转登录页面
        next({path: global.loginPage.path});
      } else {
        loadingMain(to.path);
        const path = await readRouter(to.path, to.name);
        if (path) {
          // console.log('to path -- [6]', path);
          next(path);
        } else {
          // console.log('to path next [5]', to.path);
          next();
        }
      }
    }
  } else {
    // console.log('to path next [2]', to.path);
    next();
  }
});

router.afterEach((to, from) => {
  finishLoadingBar();
  if (pathMatch.main(to.path)) {
    const appStore = useAppStore();
    appStore.addTab(to.path);
    appStore.setMainLoading(false);
  }
});

/**
 * 根据路径触发主应用区域的加载状态
 * @param path
 */
const loadingMain = (path) => {
  if (pathMatch.main(path)) {
    const appStore = useAppStore();
    appStore.setMainLoading(true);
  }
};

/**
 * guard 读取路由信息
 * @param nextPath
 * @param name
 * @returns
 */
const readRouter = async (nextPath, name?: any) => {
  const userStore = useUserStore();
  if (!userStore.hasInfo) {
    try {
      const res = await usersInfo();
      userStore.setUsersInfo(res.data);
      const usersRoutes = userStore.usersRoutes;
      if (usersRoutes.length > 0) {
        usersRoutes.forEach((route: any) => {
          router.addRoute(global.mainPage.name, route as unknown as any);
        });
        // 此处出来第一次没有路由信息的情况router会直接解析到错误页面
        if (pathMatch.errorMain(name)) {
          return nextPath;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } catch (error: any) {
      console.log('add route error -> ', error);
      // 此处出来登录失效的问题以及404
      if (error && error.status === 401) {
        userStore.clearCache();
        delTokenInfo();
        return global.loginPage.path;
      } else {
        return '/unknown';
      }
    }
  } else {
    return false;
  }
};

// 由于pinia的初始化要晚于router的初始化
// import {storeToRefs} from 'pinia';
// const tokenStore = useTokenStore();
// const {accessToken} = storeToRefs(tokenStore);
// const accessTokenStr = accessToken.value;

export default router;
